<?php
# http://projects:8081/cdapp-2kt-api/api/proxy_ntfm_setter.php

include_once '_portal.php';
// logfile('NTFM_SAVE::INPUT', json_stringify($post));

$output = [];
if (isset($post->tma)) {
  $output['tma'] = save_tma(get_object_vars($post->tma->response->data));
}
if (isset(POST_ARR['ap'])) {
  $output['ap'] = save_ap(POST_ARR['ap']);
}
if (isset($post->div)) {
  $output['div'] = save_div($post->div->response->data);
}
if (isset(POST_ARR['nrs'])) {
  $output['nrs'] = save_nrs(POST_ARR['nrs']);
}

// logfile('NTFM_SAVE::OUTPUT', json_stringify($output));
output($output);
function save_tma($response) {
  // logfile('save_tma', json_stringify($response));
  // TODO:
  return fetch_tma($response);
}

function save_ap($replies) {
  $results      = [];
  $payload_last = param('NTFM_AP_PAYLOAD_LAST');
  foreach ($replies as $ap => $reply) {
    $response     = $reply;
    $result       = fetch_ap_response($response, $payload_last[$ap], false);
    $results[$ap] = $result;
  }
  param('NTFM_AP_TIMESTAMP_RECIVE', timestamp());
  param('NTFM_AP_TIME_RECIVE', date('Y-m-d H:i:s'));
  return $results;
}

function save_div($response) {
  // logfile('NTFM_SAVE:DIV:INPUT', json_stringify($response));
  if (! is_array($response)) {
    return null;
  }

  exec_sql("CREATE TABLE IF NOT EXISTS `2kt_diversion_record` ( `id` varchar(128) COLLATE utf8_unicode_ci NOT NULL, `acid` varchar(16) COLLATE utf8_unicode_ci NOT NULL, `type` varchar(8) COLLATE utf8_unicode_ci NOT NULL, `reg` varchar(8) COLLATE utf8_unicode_ci NOT NULL, `dep` varchar(8) COLLATE utf8_unicode_ci NOT NULL, `arr` varchar(8) COLLATE utf8_unicode_ci NOT NULL, `reason` text COLLATE utf8_unicode_ci NOT NULL, `route` text COLLATE utf8_unicode_ci NOT NULL, `route2` text COLLATE utf8_unicode_ci NOT NULL, `etd` datetime NOT NULL, `eta` datetime NOT NULL, `date` date NOT NULL, `status` int(4) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci");

  $sql = [];

  foreach ($response as $cellRaw) {
    $cell            = get_object_vars($cellRaw);
    $reason          = isset($cell['reason']) ? $cell['reason'] : null;
    $arctyp          = isset($cell['arctyp']) ? $cell['arctyp'] : null;
    $code            = isset($cell['code']) ? $cell['code'] : null;
    $turb            = isset($cell['turb']) ? $cell['turb'] : null;
    $reportedCount   = isset($cell['reportedCount']) ? $cell['reportedCount'] : null;
    $flightId        = isset($cell['flightId']) ? $cell['flightId'] : null;
    $secondApplyFlag = isset($cell['secondApplyFlag']) ? $cell['secondApplyFlag'] : null;
    $acid            = isset($cell['acid']) ? $cell['acid'] : null;
    $ifTransRegion   = isset($cell['ifTransRegion']) ? $cell['ifTransRegion'] : null;
    $eobt            = isset($cell['eobt']) ? $cell['eobt'] : null;
    $regid           = isset($cell['regid']) ? $cell['regid'] : null;
    $id              = isset($cell['id']) ? $cell['id'] : null;
    $sobt            = isset($cell['sobt']) ? $cell['sobt'] : null;
    $reasonCode      = isset($cell['reasonCode']) ? $cell['reasonCode'] : null;
    $applyTime       = isset($cell['applyTime']) ? $cell['applyTime'] : null;
    $sibt            = isset($cell['sibt']) ? $cell['sibt'] : null;
    $cstat           = isset($cell['cstat']) ? $cell['cstat'] : null;
    $oroute          = isset($cell['oroute']) ? $cell['oroute'] : null;
    $identifier      = isset($cell['identifier']) ? $cell['identifier'] : null;
    $adep            = isset($cell['adep']) ? $cell['adep'] : null;
    $fDel            = isset($cell['fDel']) ? $cell['fDel'] : null;
    $transmitCount   = isset($cell['transmitCount']) ? $cell['transmitCount'] : null;
    $ifTransOma      = isset($cell['ifTransOma']) ? $cell['ifTransOma'] : null;
    $execDate        = isset($cell['execDate']) ? $cell['execDate'] : null;
    $sourceDis       = isset($cell['sourceDis']) ? $cell['sourceDis'] : null;
    $replyTime       = isset($cell['replyTime']) ? $cell['replyTime'] : null;
    $route           = isset($cell['route']) ? $cell['route'] : null;
    $atot            = isset($cell['atot']) ? $cell['atot'] : null;
    $phone           = isset($cell['phone']) ? $cell['phone'] : null;
    $replaceDis      = isset($cell['replaceDis']) ? $cell['replaceDis'] : null;
    $ades            = isset($cell['ades']) ? $cell['ades'] : null;
    $contacts        = isset($cell['contacts']) ? $cell['contacts'] : null;

    $status = intval($reportedCount) + intval($transmitCount);
    $date   = explode(' ', $execDate)[0];
    $etd    = isset($cell['eobt']) ? $cell['eobt'] : (isset($cell['sobt']) ? $cell['sobt'] : null);

    $sql[] = "REPLACE INTO `2kt_diversion_record`(`id`,`acid`,`type`,`reg`,`dep`,`arr`,`reason`,`route`,`route2`,`etd`,`eta`,`date`,`status`) VALUES ('{$identifier}','{$acid}','{$arctyp}','{$regid}','{$adep}','{$ades}','{$reason}','{$oroute}','{$route}','{$etd}','{$sibt}','{$date}',{$status})";
  }

  $result    = [];
  $exception = null;
  // logfile('NTFM_SAVE_DIV_SQL', implode("\n", $sql));

  if (count($sql) > 0) {
    exec_sql_array($sql);
    // try {
    //   exec_sql_array($sql);
    // } catch (Exception $e) {
    //   $exception = $e->getMessage();
    // }
  }
  $success = ! in_array(false, $result);
  $failed  = false;
  logfile('NTFM_SAVE:DIV:STATUS', $success);

  if ($success) {
    param('NTFM_DIV_TIMESTAMP_RECIVE', timestamp());
    param('NTFM_DIV_TIME_RECIVE', date('Y-m-d H:i:s'));
    logfile('NTFM_SAVE:DIV:SUCCESS', '已保存');
  } else {
    $failed = [];
    foreach ($result as $i => $bool) {
      if (! $bool) {
        $failed[] = $sql[$i];
      }
    }
    logfile('NTFM_SAVE:DIV:FAILED', implode(";\n", $failed));
  }

  return [
    'success'   => $success,
    'failed'    => $failed,
    'exception' => $exception,
    'sql'       => $sql,
  ];
}

function save_nrs($nrs) {
  $sqls    = [];
  $result  = true;
  $content = [];

  if (! is_null($nrs)) {
    $current      = date('Y-m-d H:i:s');
    $minute       = (int)date('i');
    $minute_piece = $minute < 15 ? '00' : ($minute < 30 ? '15' : ($minute < 45 ? '30' : '45'));
    $hour         = (int)date('H');
    $from         = date('Y-m-d H:') . $minute_piece . ':00';
    $to           = date('Y-m-d ') . ($hour < 23 ? ($hour + 1) : '00') . ':00:00';
    foreach ($nrs as $details) {
      $details['update'] = $current;
      $airport           = $details['airport'];
      $dnr_tkf           = $details['dnr_tkf'];
      $hnr_tkf           = $details['hnr_tkf'];
      // 'NORMAL_RATE_TYPES' => ['flight', 'dep', 'tkf', 'arr', 'lnd', 'start', 'release'],
      $nrs = json_stringify([
        'd' => [
          $details['dnr_flight'],
          $details['dnr_dep'],
          $details['dnr_tkf'],
          $details['dnr_arr'],
          $details['dnr_lnd'],
          $details['dnr_start'],
          $details['dnr_release'],
        ],
        'h' => [
          $details['hnr_flight'],
          $details['hnr_dep'],
          $details['hnr_tkf'],
          $details['hnr_arr'],
          $details['hnr_lnd'],
          $details['hnr_start'],
          $details['hnr_release'],
        ],
      ]);
      $sql       = "UPDATE `2kt_flow_record_airports` SET `dailyTNR`={$dnr_tkf},`hourlyTNR`='{$hnr_tkf}',`normalRates`='{$nrs}' WHERE `moment`>='{$from}' AND `moment`<='{$to}' AND `item`='{$airport}'";
      $sqls[]    = $sql;
      $result    = $result && exec_sql($sql);
      $content[] = $details;
    }
    // $result = exec_sql_array($sqls);
  }
  return [
    'result'  => $result,
    '$sql'    => $sqls,
    'content' => $content,
  ];
}

function fetch_tma($content, $ignore = 0) {
  output($content);
  if (! $content || is_null($content) || ! isset($content)) {
    // $result_ext = update_details();
    # 无 NTFM_response 的情况
    logdb('NTFM_SAVE_TMA', 'TMA无流量数据', 'ERROR');
    return [
      'status' => -2,
      'msg'    => 'Failed to load TMA data.',
    ];
  }
  // $content = get_object_vars($content);
  $all_zero   = true;
  $payload    = param('NTFM_TMA_PAYLOAD_LAST');
  $step       = $payload['step'];
  $begTime    = $payload['begTime'];
  $endTime    = $payload['endTime'];
  $count      = floor((strtotime($endTime) - strtotime($begTime)) / ($step * 60)) + 1;
  $keys       = explode(':', $payload['key']);
  $sql        = "INSERT INTO `2kt_flow_record`(`moment`, `content`, `history`) VALUES ";
  $flow_list  = [];
  $data_count = 0;
                                                                          # dispose first several cells due to bugs of NTFM
  $startIndex = param('NTFM_TMA_LOAD_HOURS_DISPOSE') * round(60 / $step); // STEP_MINUTES or $step
  for ($i = $startIndex; $i < $count; $i++) {
    $moment = date('Y-m-d H:i:s', strtotime($begTime) + $i * $step * 60);
    $flow   = [];
    foreach ($keys as $label) {
      $value  = $content[$label][$i];
      $flow[] = ($label == 'other' && $ignore) ? 0 : $value;
      $data_count++;
      $all_zero = $all_zero && ($value == 0 || $value == '0' || $value == null);
    }
    $flow_list[] = ['moment' => $moment, 'flowData' => $flow];
    $json        = json_stringify($flow);
    $sql .= "('{$moment}','{$json}','{$json}'),";
  }
  if ($all_zero) {
    # NTFM_response 全0的情况
    // logfile('NTFM_SAVE:TMA:ERR', 'NTFM_response 全0');
    logdb('NTFM_SAVE_TMA', 'TMA流量数据全部为0', 'ERROR');
    return [
      'status' => -1,
      'msg'    => 'Disposed due to invalid all 0 value.',
    ];
  } else {
    $sql     = rtrim($sql, ',');
    $updated = date('Y-m-d H:i:s');
    $sql .= " ON DUPLICATE KEY UPDATE `content` = VALUES(`content`),`updated` = '{$updated}'";
    $result          = exec_sql($sql);
    $result_ext      = update_tma_details();
    $result_his      = update_tma_history();
    $result_snapshot = make_snapshot() != null;
    # NTFM_response 正常的情况
    param('NTFM_TMA_TIMESTAMP_RECIVE', timestamp());
    param('NTFM_TMA_TIME_RECIVE', date('Y-m-d H:i:s'));
    logfile('NTFM_SAVE:TMA', '已保存');
    return [
      'status'         => 1,
      'fetchStatus'    => $result,
      'historyStatus'  => $result_his,
      'detailsStatus'  => $result_ext,
      'snapshotStatus' => $result_snapshot, // snapshot 应在 details 之后, 否则无法记录详细信息
       'countCell'      => $data_count,
      'countLine'      => $count,
      // 'rawData' => $flow_list,
    ];
  }
}

function update_tma_history() {
  # Update history data
  // obsolete computing for history threshold
  // $history_threshold = date('Y-m-d H:i:s', time() + HISTORY_LOCK_HOURS + 3600);
  # 每日0400前更新当日0400含以后的计划架次，0400后更新次日计划架次
  $history_threshold = date('Y-m-d') . ' ' . param('NTFM_HISTORY_LOCK_MOMENT');
  if (time() > strtotime($history_threshold)) {
    $history_threshold = date('Y-m-d', strtotime("tomorrow")) . ' ' . param('NTFM_HISTORY_LOCK_MOMENT');
  }
  $sql_his    = "UPDATE `2kt_flow_record` SET `history`=`content` WHERE `moment` >= '{$history_threshold}'";
  $result_his = exec_sql($sql_his);
  return $result_his;
}

function update_tma_details($output_only = false) {
  $minute         = (int)date('i');
  $minute         = $minute < 15 ? 0 : (($minute < 30 ? 15 : ($minute < 45 ? 30 : 45)));
  $moment         = date('Y-m-d H:') . $minute . ':00';
  $sector         = 0;
  $rwy_code_zuuu  = param('ATCOS_RWY_MODE_CODE_ZUUU');
  $rwy_code_zutf  = param('ATCOS_RWY_MODE_CODE_ZUTF');
  $direction_zuuu = substr($rwy_code_zuuu, 0, 1);
  $direction_zutf = substr($rwy_code_zutf, 0, 1);
  $utilize_zuuu_w = substr($rwy_code_zuuu, 1, 1);
  $utilize_zuuu_e = substr($rwy_code_zuuu, 2, 1);
  $utilize_zutf_w = substr($rwy_code_zutf, 1, 1);
  $utilize_zutf_e = substr($rwy_code_zutf, 2, 1);
  $utilize_zutf_n = substr($rwy_code_zutf, 3, 1);
  $rwy_utilize    = [
    'zuuu' => [
      'direction' => $direction_zuuu,
      'code'      => $rwy_code_zuuu,
      'detail'    => [
        'W'   => $utilize_zuuu_w,
        'E'   => $utilize_zuuu_e,
        '02L' => $direction_zuuu == 'N' ? ($utilize_zuuu_w == '1' ? ['D'] : ($utilize_zuuu_w == '2' ? ['A'] : ($utilize_zuuu_w == '3' ? ['A', 'D'] : []))) : [],
        '02R' => $direction_zuuu == 'N' ? ($utilize_zuuu_e == '1' ? ['D'] : ($utilize_zuuu_e == '2' ? ['A'] : ($utilize_zuuu_e == '3' ? ['A', 'D'] : []))) : [],
        '20R' => $direction_zuuu == 'S' ? ($utilize_zuuu_w == '1' ? ['D'] : ($utilize_zuuu_w == '2' ? ['A'] : ($utilize_zuuu_w == '3' ? ['A', 'D'] : []))) : [],
        '20L' => $direction_zuuu == 'S' ? ($utilize_zuuu_e == '1' ? ['D'] : ($utilize_zuuu_e == '2' ? ['A'] : ($utilize_zuuu_e == '3' ? ['A', 'D'] : []))) : [],
      ]
    ],
    'zutf' => [
      'direction' => $direction_zuuu,
      'code'      => $rwy_code_zutf,
      'runway'    => [
        'W'  => $utilize_zutf_w,
        'E'  => $utilize_zutf_e,
        'N'  => $utilize_zutf_n,
        '01' => $rwy_code_zutf == 'N' ? ($utilize_zutf_w == '1' ? ['D'] : ($utilize_zutf_w == '2' ? ['A'] : ($utilize_zutf_w == '3' ? ['A', 'D'] : []))) : [],
        '02' => $rwy_code_zutf == 'N' ? ($utilize_zutf_e == '1' ? ['D'] : ($utilize_zutf_e == '2' ? ['A'] : ($utilize_zutf_e == '3' ? ['A', 'D'] : []))) : [],
        '19' => $rwy_code_zutf == 'S' ? ($utilize_zutf_w == '1' ? ['D'] : ($utilize_zutf_w == '2' ? ['A'] : ($utilize_zutf_w == '3' ? ['A', 'D'] : []))) : [],
        '20' => $rwy_code_zutf == 'S' ? ($utilize_zutf_e == '1' ? ['D'] : ($utilize_zutf_e == '2' ? ['A'] : ($utilize_zutf_e == '3' ? ['A', 'D'] : []))) : [],
        '11' => $utilize_zutf_n == '1' ? ['D'] : ($utilize_zutf_n == '2' ? ['A'] : ($utilize_zutf_n == '3' ? ['A', 'D'] : [])),

      ],
    ],
  ];
  $mode = $direction_zuuu . $direction_zutf;

  // 查询开放的席位数
  // 有扇区 且 有人打卡 且 记入扇区数量 且 为TMA分组
  $seats = [];
  $users = [];
  $sql   = "SELECT `seatName`,  `sectorCodes`, `users` FROM `2kt_seat_status` WHERE `sectorYes` = 1 AND `sectorCodes` != '[]' AND `users` != '[]' AND `orgGroup` = 'TMA'";
  $res   = query_parse(exec_sql($sql));
  foreach ($res as $cell) {
    if ($cell['sectorCodes'] && count($cell['sectorCodes']) > 0) {
      $sector++;
      $seats[$cell['seatName']] = $cell['sectorCodes'];
      $users[$cell['seatName']] = [];
      foreach ($cell['users'] as $user) {
        $users[$cell['seatName']][] = $user['userName'];
      }
    }
  }

  // 查询带班席位
  // 有人打卡 且 为TMA分组 且 名称为 SUP/OMA

  $supervisors = [];
  $sql         = "SELECT `seatName`, `users` FROM `2kt_seat_status` WHERE (`seatName` LIKE '%SUP%' OR `seatName` LIKE '%OMA%') AND JSON_LENGTH(`users`) > 0 AND `orgGroup` = 'TMA'";
  $res         = query_parse(exec_sql($sql));
  foreach ($res as $cell) {
    $supervisors[$cell['seatName']] = [];
    foreach ($cell['users'] as $user) {
      if ($user['seatRole'] != '学员') {
        // $user['seatRole'] == '放单' || $user['seatRole'] == '管制' || $user['seatRole'] == '教员'
        $supervisors[$cell['seatName']][] = $user['userName'];
      }
    }
  }

  // 独立进近
  // @2024-09-10
  $misc_seats  = "'" . implode("','", param('MISC_SEATS')) . "'";
  $sql         = "SELECT `seatName`, `users` FROM `2kt_seat_status` WHERE `seatName` IN ($misc_seats) AND JSON_LENGTH(`users`) > 0 AND `orgGroup` = 'TMA'";
  $seats_extra = [];
  $is_ipia     = 0;
  $res         = query_parse(exec_sql($sql));
  foreach ($res as $cell) {
    $seats_extra[] = $cell['seatName'];
    if ($cell['seatName'] == 'ZUTFNTZ') {
      $is_ipia = 1;
    }
  }

  #activity
  $activity = [];
  $sql      = "SELECT DISTINCT `arrField`, `depField` FROM `2kt_activity_military`";
  $res      = exec_sql($sql);
  if ($res) {
    foreach ($res as $cell) {
      if (! in_array($cell['arrField'], $activity)) {
        $activity[] = $cell['arrField'];
      }
      if (! in_array($cell['depField'], $activity)) {
        $activity[] = $cell['depField'];
      }
      if (($cell['depField'] == '温江' || $cell['depField'] == '温江') && strlen($mode) == 2) {
        $mode .= 'WJ';
      }
    }
  }

  $details = [
    'direction'     => [
      'ZUUU' => $direction_zuuu,
      'ZUTF' => $direction_zutf,
    ],
    'runwayCodes'   => [
      'ZUUU' => $rwy_code_zuuu,
      'ZUTF' => $rwy_code_zutf,
    ],
    'runwayUtilize' => $rwy_utilize,
    'sectorCount'   => $sector,
    'activity'      => $activity,
    'seats'         => $seats,
    'users'         => $users,
    'supervisors'   => $supervisors,
    'ExtraSeats'    => $seats_extra,
    'isIPIA'        => $is_ipia,
  ];
  if ($output_only) {
    return $details;
  } else {
    # update data
    $details = json_stringify($details);
    $sql     = "UPDATE `2kt_flow_record` SET `sector`={$sector},`mode`='{$mode}',`details`='{$details}' WHERE `moment`='{$moment}'";

    # 2025-04-23, Check error in update detail
    logfile('TMA_DETAILS', $details);
    logfile('TMA_DETAILS_SQL_UPDATE', $sql);
    return exec_sql($sql);
  }
}

function make_snapshot() {
  // 快照时间
  $minute        = intval(date('i'));
  $target_minute = $minute < 15 ? '00' : ($minute < 30 ? '15' : ($minute < 45 ? '30' : '45'));
  $snapTime      = date('Y-m-d H') . ':' . $target_minute . ':00';
  $snapData      = null;
  // 检查是否已经存在当前时刻快照数据
  $sql       = "SELECT COUNT(*) FROM `2kt_flow_record_snapshot` WHERE `snapTime` = '{$snapTime}'";
  $isExisted = exec_sql($sql)[0]['COUNT(*)'] > 0;
  if (! $isExisted) {
    // 设置起止范围
    // 当前时间-4小时, 以整点为单位
    $begTime = date('Y-m-d H', time() - param('NTFM_SNAPSHOT_HOURS_BEFORE') * 3600) . ':00:00';
    // 当前时间+20小时, 以整点为单位
    $endTime    = date('Y-m-d H', time() + param('NTFM_SNAPSHOT_HOURS_AFTER') * 3600) . ':00:00';
    $updateTime = date('Y-m-d H:i:s');
    // 检索对应 moment 段内的 cotent 字段
    $sql    = "SELECT `content` FROM `2kt_flow_record` WHERE `moment` >= '{$begTime}' AND `moment`<='{$endTime}'";
    $result = exec_sql($sql);
    // 生成&记录当前运行模式
    $details = json_stringify(update_tma_details(true));
    if ($result) {
      // 如果表格不存在则新建表格
      create_snapshot_table();
      $snapData = json_stringify(query_parse($result));
      // 如果流量数据表检索到数据, 则转换为 JSON 保存到快照表内, 仅保存起始时刻 moment
      $sql = "INSERT INTO `2kt_flow_record_snapshot`(`snapTime`, `begTime`, `snapData`, `details`, `updateTime`) VALUES ('{$snapTime}','{$begTime}','{$snapData}','{$details}','{$updateTime}')";
      exec_sql($sql);
    }
  }
  return $snapData;
}

function create_snapshot_table() {
  $sql = "CREATE TABLE IF NOT EXISTS `2kt_flow_record_snapshot` (
    `snapTime` datetime NOT NULL,
    `begTime` datetime NOT NULL,
    `snapData` json DEFAULT NULL,
    `updateTime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`snapTime`)
   ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
  return exec_sql($sql);
}

function fetch_ap_response($response, $payload, $ignore = 0) {
  if (! $response || $response == null || ! isset($response)) {
    // $result_ext = update_details();
    # 无 NTFM_response 的情况
    logdb('NTFM_SAVE_AP', $payload['item'] . '无流量数据', 'ERROR');
    return [
      'requestDuration' => 0,
      'requestStatus'   => false,
      'fetchDuration'   => 0,
      'fetchStatus'     => false,
      // 'detailsStatus' => $result_ext,
       'countCell'       => 0,
      'countLine'       => 0,
      'rawData'         => [],
    ];
  }
  $all_zero  = true;
  $timestamp = timestamp();
  $item      = $payload['item'];
  $step      = $payload['step'];
  $begTime   = $payload['begTime'];
  $endTime   = $payload['endTime'];
  $count     = floor((strtotime($endTime) - strtotime($begTime)) / ($step * 60)) + 1;
  $keys      = explode(':', $payload['key']);
  $data      = $response['response']['data'];
  $sql       = "INSERT INTO `2kt_flow_record_airports`(`moment`, `item`, `content`, `history`, `mixKey`) VALUES ";
  $output    = [];
  $dataCount = 0;
                                                                          # dispose first several cells due to bugs of NTFM
  $startIndex = param('NTFM_TMA_LOAD_HOURS_DISPOSE') * round(60 / $step); // STEP_MINUTES or $step
  for ($i = $startIndex; $i < $count; $i++) {
    $stamp   = strtotime($begTime) + $i * $step * 60;
    $moment  = date('Y-m-d H:i:s', $stamp);
    $content = [];
    foreach ($keys as $label) {
      $label = strpos($label, 'OTHER') ? 'other' : $label;
      $value = $data['arr'][$label][$i] + $data['dep'][$label][$i];
      // $content[] = ($label == 'other' && $ignore) ? 0 : $value;
      $content[] = $value;
      $dataCount++;
      $all_zero = $all_zero && ($value == 0 || $value == '0' || $value == null);
    }
    $output[]     = ['moment' => $moment, 'content' => $content];
    $content_json = json_stringify($content);
    $mix_key      = "{$stamp}.{$item}";
    $sql .= "('{$moment}','{$item}','{$content_json}','{$content_json}','{$mix_key}'),";
  }
  if ($all_zero) {
    // $result_ext = update_details();
    # NTFM_response 全0的情况
    logdb('NTFM_SAVE_AP', $payload['item'] . '流量数据全部为0', 'WARNING');
    return [
      // 'tags' => $tags,
       //  'requestDuration' => $payload['duration'],
       'requestStatus' => false,
      'fetchDuration' => timestamp() - $timestamp,
      'fetchStatus'   => false,
      // 'detailsStatus' => $result_ext,
       'countCell'     => $dataCount,
      'countLine'     => $count,
      'rawData'       => $output,
      // 'sql' => $sql,
    ];
  } else {
    $sql     = rtrim($sql, ',');
    $updated = date('Y-m-d H:i:s');
    $sql .= " ON DUPLICATE KEY UPDATE `content` = VALUES(`content`),`updated` = '{$updated}'";
    $result = exec_sql($sql);
    # NTFM_response 正常的情况
    return [
      // 'tags' => $tags,
       //  'requestDuration' => $payload['duration'],
       'requestStatus' => true,
      'fetchDuration' => timestamp() - $timestamp,
      'fetchStatus'   => $result,
      // 'detailsStatus' => $result_ext,
       // 'historyStatus' => $result_his,
       'countCell'     => $dataCount,
      'countLine'     => $count,
      'rawData'       => $output,
      // 'sql' => $sql,
    ];
  }
}